<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css"
	href="styles/importArticle.css">
</head>
<body>
	<div style="height: 86px">
		<div id="title" style="height: 50px; width: 100%">
			<input placeholder="请输入标题..." id="titleName"
				style="height: 48px; width: 100%; border: none; font-size: 28px"
				type="text" />
		</div>

		<div class="tags" id="tags" tabindex="1">
			<input id="form-field-tags" type="text" placeholder="请输入标签 ..."
				value="Tag Input Control" name="tags" style="display: none;">
			<input type="text" placeholder="请输入标签 ..." class="tags_enter"
				autocomplete="off">
		</div>
	</div>
	<div id="editZoom">
		<div id="editTool" class="toolbar"></div>
		<div id="editContent" class="text">
			<p>请输入内容</p>
		</div>
	</div>
	<script type="text/javascript"
		src="./wangEditor-3.0.15/release/wangEditor.js"></script>

	<script type="text/javascript" src="scripts/base.js"></script>

	<script>
		var articleId = null;
		var editor = null;
		$(function() {
			initCkedit();
			$('#importBtn').bind('click', uploadArticle);
			$(".tags_enter").blur(function() { //焦点失去触发 
				var txtvalue = $(this).val().trim();
				if (txtvalue != '') {
					addTag($(this));
					$(this).parents(".tags").css({
						"border-color" : "#d5d5d5"
					})
				}else{
					$(this).val('');
				}
			}).keydown(function(event) {
				var key_code = event.keyCode;
				var txtvalue = $(this).val().trim();
				if (key_code == 13 && txtvalue != '') { //enter
					addTag($(this));
				}
				if (key_code == 32 && txtvalue != '') { //space
					addTag($(this));
				}
			});
			$("#tags").on('click','.close',function() {
				$(this).parent(".tag").remove();
			});
			
			$(".tags").click(function() {
				$(this).css({
					"border-color" : "#f59942"
				})
			}).blur(function() {
				$(this).css({
					"border-color" : "#d5d5d5"
				})
			})

		});

		function uploadArticle() {

			var contents = editor.txt.html();
			var title = $("#titleName").val().trim();
			if (title == null || title.length == 0 || title == undefined) {
				messageShow("文章", "未输入标题,请输入标题!");
				return;
			}

			var menu = $("#menu").tree("getSelected");
			if (menu == null || menu.length == 0 || menu == undefined) {
				messageShow("文章", "未选择文章种类,请在左侧选择文章的类别!");
				return;
			}

			var authorId = getCookie("userId");
			var category = '文章';
			var tagsName = getAllTags();
			var menuId = menu.id;

			saveArticle(articleId, authorId, title, contents, category,
					tagsName, menuId);
			$('#importBtn').unbind('click');
			top.location.href = "personalCenter.html";
		}

		function initCkedit() {
			var E = window.wangEditor;
			editor = new E('#editTool', '#editContent');
			editor.customConfig.uploadImgShowBase64 = true; // 使用 base64 保存图片

			editor.customConfig.menus = [ 'head', // 标题
			'bold', // 粗体
			'italic', // 斜体
			'underline', // 下划线
			'strikeThrough', // 删除线
			'foreColor', // 文字颜色
			'backColor', // 背景颜色
			'link', // 插入链接
			'list', // 列表
			'justify', // 对齐方式
			'quote', // 引用
			'emoticon', // 表情
			'image', // 插入图片
			'table', // 表格
			'code', // 插入代码
			'undo', // 撤销
			'redo' // 重复
			]

			editor.customConfig.uploadImgServer = 'Img/upload.do'; // 上传URL
			editor.customConfig.uploadImgMaxSize = 5 * 1024 * 1024;
			editor.customConfig.uploadFileName = 'imageName';
			editor.customConfig.uploadImgHooks = {
				customInsert : function(insertImg, result, editor) {
					// 图片上传并返回结果，自定义插入图片的事件（而不是编辑器自动插入图片！！！）
					// insertImg 是插入图片的函数，editor 是编辑器对象，result 是服务器端返回的结果

					// 举例：假如上传图片成功后，服务器端返回的是 {url:'....'} 这种格式，即可这样插入图片：
					var url = result.data;
					insertImg(url);
					// result 必须是一个 JSON 格式字符串！！！否则报错
				}
			}

			editor.create();

			// 检查是否有草稿
			checkDraft();

			// 设置文章的id;
			if (articleId == null) {
				articleId = GenNonDuplicateID(3);
			}

			document.getElementById('editContent').addEventListener(
					'click',
					function() {
						var contents = editor.txt.html();
						var title = $("#titleName").val();
						var authorId = getCookie("userId");
						
						var category = '草稿';
						var tagsName = getAllTags();

						var menu = $("#menu").tree("getSelected");
						var menuId = "";
						if (menu != null) {
							menuId = menu.id;
						}

						saveArticle(articleId, authorId, title, contents,
								category, tagsName, menuId);
					});

		}
		function saveArticle(articleId, authorId, title, contents, category,
				tagsName, menuId) {
			var articleId_ = encodeURI(articleId, "UTF-8");
			var authorId_ = encodeURI(authorId, "utf-8");
			var title_ = encodeURI(title, "utf-8");
			var contents_ = encodeURI(contents, "utf-8");
			var category_ = encodeURI(category, "utf-8");
			var tagsName_ = encodeURI(tagsName, "utf-8");
			var menuId_ = encodeURI(menuId, "utf-8");

			var datas = {
				'articleId' : articleId_,
				'authorId' : authorId_,
				'title' : title_,
				'cont' : contents_,
				'menuId' : menuId_,
				'tagIds' : tagsName_,
				'category' : category_
			};

			$.ajax({
				url : 'article/saveArticle.do',
				data : datas,
				type : 'post',
				dataType : 'json',
				success : function(result) {
					if (result.state == 0) {
						console.log("文章保存成功!");
					}
				},
				error : function(e) {
					messageShow("文章", "保存文章失败!");
				}
			});

		}
		//检查是否有草稿,如有,将草稿填充到编辑框
		function checkDraft() {
			var authorId = getCookie("userId");
			var datas = {
				'authorId' : authorId,
			};
			$.ajax({
				url : 'article/checkDraft.do',
				data : datas,
				type : 'post',
				dataType : 'json',
				success : function(result) {
					if (result.state == 0) {
						var draft = result.data;
						console.log(draft);
						$("#menu").tree({
							method : "POST",
							url : "menu/showMenuTree.do",
							onClick : function(node) {
							},
							loadFilter : function(data, parent) {
								return data.data;
							},
							onLoadSuccess : function(node, data) {
								if (draft != null) {

									var content = draft.content;
									editor.txt.html(content);
									$("#titleName").val(draft.title);
									articleId = draft.id;
									//将标签写入标签框	
									if (draft.tagId != null) {
										insertTags(draft.tagId);
									}
									if (draft.menuId != null) {
										selectMenu(draft.menuId);
									} else {
										var root = $('#menu').tree('find', 1);
										$("#menu").tree('expand', root.target);
									}

								} else {
									var root = $('#menu').tree('find', 1);
									$("#menu").tree('expand', root.target);
								}

							}
						});
					}
				},
				error : function(e) {
					alert("通信失败!");
				}
			});
		};

		function showMenu() {

			$("#menu").tree({
				method : "POST",
				url : "menu/showMenuTree.do",
				onClick : function(node) {
				},
				loadFilter : function(data, parent) {
					return data.data;
				}
			});

		}

		function selectMenu(menuId) {
			var select = $('#menu').tree('find', menuId);
			console.log(select);

			$("#menu").tree('expandTo', select.target);
			$("#menu").tree('select', select.target);

		};

		function insertTags(tagNames) {
			var tags = tagNames.split(",");
			for (var i = 0; i < tags.length; i++) {
				generateTag(tags[i]);
			}
		}

		function addTag(obj) {
			var tag = obj.val().trim();
			if (tag != '') {
				var i = 0;
				$(".tag").each(function() {
					if ($(this).text().trim() == tag + "×") {
						$(this).addClass("tag-warning");
						setTimeout("removeWarning()", 400);
						i++;
					}
				})
				obj.val('');
				if (i > 0) { //说明有重复
					return false;
				}
				$("#form-field-tags")
						.before(
								"<span class='tag'>"
										+ tag
										+ "<button class='close' type='button'>×</button></span>"); //添加标签

			}else{
				obj.val('');
			}
		};

		//根据标签名称生成标签
		function generateTag(tagName) {
			var tag = tagName.trim();
			if (tag != '') {
				$("#form-field-tags")
						.before(
								"<span class='tag'>"
										+ tag
										+ "<button class='close' type='button'>×</button></span>"); //添加标签

			}
		};

		function getAllTags() {

			var tags = $('.tag');
			var tagsName = "";
			for (var i = 0; i < tags.length; i++) {
				var tag = $(tags[i]).text();
				var tagName = tag.substring(0, tag.length - 1);
				tagsName += tagName + ",";
			}
			if (tagsName.length > 0) {
				tagsName = tagsName.substring(0, tagsName.length - 1);
			}
			return tagsName;
		}

		function removeWarning() {
			$(".tag-warning").removeClass("tag-warning");
		};

		//获取不重复字符串
		function GenNonDuplicateID(randomLength) {
			return Number(
					Math.random().toString().substr(3, randomLength)
							+ Date.now()).toString(36)
		};
	</script>
</body>
</html>